package nlptools.i2b2;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.regex.Pattern;

public class PatternFactory
{
	private static StringLengthComparator	slc	= new StringLengthComparator();
	
	private static ArrayList<String> readLines(File input) throws IOException
	{
		ArrayList<String> lines = new ArrayList<String>();
		BufferedReader br = new BufferedReader(new FileReader(input));
		String line = null;
		while ((line = br.readLine()) != null)
		{
			if (line.trim().length() == 0)
				continue;
			lines.add(line);
		}
		br.close();
		return lines;
	}
	
	private static Pattern makePattern(ArrayList<String> lines)
	{
		if (lines.size() == 0)
			return null;
		
		Collections.sort(lines, slc);
		Collections.reverse(lines);
		
		StringBuilder sb = new StringBuilder();
		
		for (String s : lines)
		{
			sb.append(s);
			sb.append('|');
		}
		
		String ps = sb.toString();
		ps = ps.substring(0, ps.length() - 1);
		
		Pattern p = Pattern.compile(ps, Pattern.CASE_INSENSITIVE);
		return p;
	}
	
	public static Pattern createPattern(ArrayList<File> inputs)
			throws IOException
	{
		ArrayList<String> lines = new ArrayList<String>();
		for (File input : inputs)
		{
			lines.addAll(readLines(input));
		}
		
		return makePattern(lines);
		
	}
	
	public static Pattern createPattern(File input) 
	{
		ArrayList<String> lines;
		try {
			lines = readLines(input);
			if (lines.size() == 0)
				return null;
			return makePattern(lines);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
		
		
	}
}

